/**
 * 服务相关的自定义Hook
 *
 * 提供服务数据的获取和管理功能
 */
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../services/api';
import { Service, ServiceCreate, ServiceUpdate, PaginatedResponse, ServiceCategory } from '../types';

// 服务列表参数接口
export interface ServiceListParams {
  page?: number;
  size?: number;
  category?: string;
  active_only?: boolean;
  featured_only?: boolean;
}

// 查询键常量
const QUERY_KEYS = {
  services: ['services'] as const,
  service: (id: number) => ['services', id] as const,
  categories: ['services', 'categories'] as const,
};

// 服务API函数
const serviceApi = {
  getServices: async (params: ServiceListParams = {}): Promise<PaginatedResponse<Service>> => {
    const queryParams = new URLSearchParams();
    if (params.page) queryParams.append('page', String(params.page));
    if (params.size) queryParams.append('size', String(params.size));
    if (params.category) queryParams.append('category', params.category);
    if (params.active_only !== undefined) queryParams.append('active_only', String(params.active_only));
    if (params.featured_only !== undefined) queryParams.append('featured_only', String(params.featured_only));

    const url = `/api/services/?${queryParams.toString()}`;
    return api.get<PaginatedResponse<Service>>(url);
  },

  getService: async (id: number): Promise<Service> => {
    return api.get<Service>(`/api/services/${id}`);
  },

  getCategories: async (): Promise<ServiceCategory[]> => {
    return api.get<ServiceCategory[]>('/api/services/categories');
  },

  createService: async (data: ServiceCreate): Promise<Service> => {
    return api.post<Service>('/api/services', data);
  },

  updateService: async (id: number, data: ServiceUpdate): Promise<Service> => {
    return api.put<Service>(`/api/services/${id}`, data);
  },

  deleteService: async (id: number): Promise<{ message: string }> => {
    return api.delete<{ message: string }>(`/api/services/${id}`);
  },
};

/**
 * 获取服务列表
 */
export const useServices = (params: ServiceListParams = {}) => {
  return useQuery({
    queryKey: [...QUERY_KEYS.services, params],
    queryFn: () => serviceApi.getServices(params),
    staleTime: 5 * 60 * 1000, // 5分钟内数据被认为是新鲜的
  });
};

/**
 * 获取单个服务详情
 */
export const useService = (id: number) => {
  return useQuery({
    queryKey: QUERY_KEYS.service(id),
    queryFn: () => serviceApi.getService(id),
    enabled: !!id,
  });
};

/**
 * 获取服务分类
 */
export const useServiceCategories = () => {
  return useQuery({
    queryKey: QUERY_KEYS.categories,
    queryFn: () => serviceApi.getCategories(),
    staleTime: 10 * 60 * 1000, // 10分钟内数据被认为是新鲜的
  });
};

/**
 * 获取推荐服务（用于前台显示）
 */
export const useFeaturedServices = (limit: number = 6) => {
  return useQuery({
    queryKey: [...QUERY_KEYS.services, 'featured', limit],
    queryFn: () => serviceApi.getServices({
      featured_only: true,
      active_only: true,
      size: limit
    }),
    staleTime: 10 * 60 * 1000,
    select: (data) => data.items, // 只返回items数组
  });
};

/**
 * 创建服务
 */
export const useCreateService = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: ServiceCreate) => serviceApi.createService(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.services });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.categories });
    },
  });
};

/**
 * 更新服务
 */
export const useUpdateService = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: ServiceUpdate }) =>
      serviceApi.updateService(id, data),
    onSuccess: (updatedService) => {
      queryClient.setQueryData(
        QUERY_KEYS.service(updatedService.id),
        updatedService
      );
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.services });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.categories });
    },
  });
};

/**
 * 删除服务
 */
export const useDeleteService = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: number) => serviceApi.deleteService(id),
    onSuccess: (_, deletedId) => {
      queryClient.removeQueries({ queryKey: QUERY_KEYS.service(deletedId) });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.services });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.categories });
    },
  });
};

/**
 * 服务管理的综合Hook
 */
export const useServiceManagement = () => {
  const createMutation = useCreateService();
  const updateMutation = useUpdateService();
  const deleteMutation = useDeleteService();

  return {
    // 创建
    createService: createMutation.mutate,
    isCreating: createMutation.isPending,
    createError: createMutation.error,

    // 更新
    updateService: updateMutation.mutate,
    isUpdating: updateMutation.isPending,
    updateError: updateMutation.error,

    // 删除
    deleteService: deleteMutation.mutate,
    isDeleting: deleteMutation.isPending,
    deleteError: deleteMutation.error,

    // 重置错误状态
    resetErrors: () => {
      createMutation.reset();
      updateMutation.reset();
      deleteMutation.reset();
    },
  };
};